<script setup lang="ts">
import {
  QueryType,
  type BusData,
  type CustomerData,
  type FlightData,
  type HotelData,
  type AnyData
} from "../../../types/DataTypes.ts"
import { inject, ref, watch } from "vue";
import { api } from "../../../api/Api.ts"
import { DataKey, type DataKeyType } from "../../../types/KeyTypes.ts";
import { useAuthStore } from '../../../stores/authStore.ts'

const props = defineProps<{
  queryType: QueryType,
  showReservation: boolean,
  reservationData: AnyData
}>()

const emit = defineEmits<{
  'cancel': [boolean]
}>()

const { isNeedUpdate } = inject<DataKeyType>(DataKey) as DataKeyType;

const loading = ref(false);
// 预约数据
const busData = ref<BusData>({
  location: '',
  price: 0,
  availBus: 0,
  totalBus: 10
})

const flightData = ref<FlightData>({
  flightNum: '',
  fromCity: '',
  arivCity: '',
  price: 0.00,
  availSeat: 0,
  totalSeat: 100
})

const hotelData = ref<HotelData>({
  location: '',
  price: 0.00,
  availRoom: 0,
  totalRoom: 50
})

// 用户输入信息
const authStore = useAuthStore();
const customerData = ref<CustomerData>({
  customerName: authStore.getCustomerName,
  customerId: authStore.getCustomerId
})

// 监听传入的数据变化
watch(() => props.reservationData, (newVal: AnyData) => {
  if (!newVal) return;
  switch (props.queryType) {
    case QueryType.BusQuery:
      Object.assign(busData.value, newVal as BusData);
      break;
    case QueryType.FlightQuery:
      Object.assign(flightData.value, newVal as FlightData);
      break;
    case QueryType.HotelQuery:
      Object.assign(hotelData.value, newVal as HotelData);
      break;
  }
})

// 取消预约
const handleCancel = () => {
  emit('cancel', false)
}


// 巴士预约
const handleBusReservation = async () => {
  loading.value = true;
  try {
    // 调用预约API
    const response = await api.reservation.addReservation(
        customerData.value.customerName,
        2, // 预约类型: 2表示巴士预约
        busData.value.location
    );

    if (response.success) {
      ElMessage.success('巴士预约成功');
      emit('cancel', false);
      isNeedUpdate.value = true;
    }else {
      ElMessage.error('巴士预约失败: ' + (response.message || ''));
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 航班预约
const handleFlightReservation = async () => {
  loading.value = true;
  try {
    // 调用预约API
    const response = await api.reservation.addReservation(
        customerData.value.customerName,
        1, // 预约类型: 2表示航班预约
        flightData.value.flightNum
    );

    if (response.success) {
        ElMessage.success('航班预约成功');
        emit('cancel', false);
        isNeedUpdate.value = true;
      } else {
      ElMessage.error('航班预约失败: ' + (response.message || ''));
    }
  } catch (error) {
    console.error('预约航班出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 酒店预约
const handleHotelReservation = async () => {
  loading.value = true;
  try {
    // 调用预约API
    const response = await api.reservation.addReservation(
        customerData.value.customerName,
        3, // 预约类型: 3表示酒店预约
        hotelData.value.location
    );

    if (response.success) {
      ElMessage.success('酒店预约成功');
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error('酒店预约失败: ' + (response.message || ''));
    }
  } catch (error) {
    console.error('预约酒店出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 处理预约
const handleReservation = async () => {
  // 根据类型进行预约
  switch (props.queryType) {
    case QueryType.BusQuery:
      await handleBusReservation();
      break;
    case QueryType.FlightQuery:
      await handleFlightReservation();
      break;
    case QueryType.HotelQuery:
      await handleHotelReservation();
      break;
    default:
      ElMessage.warning('不支持的预约类型');
      break;
  }
}
</script>

<template>
  <el-dialog
      :model-value="showReservation"
      :title="`预约${queryType === QueryType.BusQuery ? '巴士' : queryType === QueryType.FlightQuery ? '航班' : '酒店'}`"
      width="400"
      :before-close="handleCancel"
  >
    <!-- 巴士预约 -->
    <el-form
        v-if="queryType===QueryType.BusQuery"
        :model="busData"
        label-width="100px"
    >
      <el-form-item label="地点">
        <el-input v-model="busData.location" disabled />
      </el-form-item>
      <el-form-item label="价格">
        <el-input-number
            v-model="busData.price"
            :step="5"
            :min="0"
            disabled
            :controls="false"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="巴士剩余">
        <el-input-number
            v-model="busData.availBus"
            :step="1"
            :max="busData.totalBus"
            :min="0"
            disabled
            :controls="false"
        />
      </el-form-item>
    </el-form>

    <!-- 航班预约 -->
    <el-form
        v-else-if="queryType === QueryType.FlightQuery"
        :model="flightData"
        label-width="100px"
    >
      <el-form-item label="航班号">
        <el-input v-model="flightData.flightNum" disabled />
      </el-form-item>
      <el-form-item label="出发城市">
        <el-input v-model="flightData.fromCity" disabled />
      </el-form-item>
      <el-form-item label="到达城市">
        <el-input v-model="flightData.arivCity" disabled />
      </el-form-item>
      <el-form-item label="价格">
        <el-input-number
            v-model="flightData.price"
            :min="0"
            :precision="2"
            disabled
            controls-position="right"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="可用座位">
        <el-input-number
            v-model="flightData.availSeat"
            :min="0"
            disabled
            controls-position="right"
        />
      </el-form-item>
    </el-form>

    <!-- 酒店预约 -->
    <el-form
        v-else-if="queryType === QueryType.HotelQuery"
        :model="hotelData"
        label-width="100px"
    >
      <el-form-item label="位置">
        <el-input v-model="hotelData.location" disabled />
      </el-form-item>
      <el-form-item label="价格">
        <el-input-number
            v-model="hotelData.price"
            :min="0"
            :precision="2"
            disabled
            controls-position="right"
        >
          <template #suffix>
            <span>元/晚</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="可用房间">
        <el-input-number
            v-model="hotelData.availRoom"
            :min="0"
            disabled
            controls-position="right"
        />
      </el-form-item>
    </el-form>

    <!-- 用户信息输入 -->
    <el-divider />
    <h4>用户信息</h4>
    <el-form :model="customerData" label-width="100px">
      <el-form-item label="客户姓名" required>
        <el-input
            v-model="customerData.customerName"
            placeholder="请输入客户姓名"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="default" @click="handleCancel" :disabled="loading">取消预约</el-button>
        <el-button
            type="primary"
            @click="handleReservation"
            :loading="loading"
            :disabled="!customerData.customerName"
        >
          确认预约
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
h4 {
  margin: 15px 0;
  color: #606266;
}
</style>